package com.misolab.android.http;

import java.util.LinkedList;

import com.misolab.android.log.Logger;

public abstract class PoolWorker implements Runnable {

	final static String ClassName = PoolWorker.class.getSimpleName();
	void logInfo(String functionName){
		Logger.i(ClassName+"::"+functionName);
	}

	String tag;
	LinkedList<String> workQueue = new LinkedList<String>();
	Thread workThread = null;
	String requestUrl;
	boolean runThread = false;

	@Override
	public void run() {
		while (workQueue.size() > 0 && runThread) {
			synchronized (workQueue) {
				requestUrl = workQueue.remove();
			}
			doWork(requestUrl);
		}
	}

	
	public String getTag() {
		logInfo("getTag");
		return tag;
	}
	public void setTag(String tag) {
		logInfo("setTag");
		this.tag = tag;
	}

	public String getRequestUrl() {
		logInfo("getRequestUrl");
		return requestUrl;
	}
	public void setRequestUrl(String requestUrl) {
		logInfo("setRequestUrl");
		this.requestUrl = requestUrl;
	}


	public void addRequest(String url) {
		logInfo("addRequest");
		Logger.d(url);

		synchronized (workQueue) {			
			workQueue.add(url);
			Logger.d(""+workQueue.size());
		}

		if (workThread == null) {
			workThread = new Thread(this);
			runThread = true;
			workThread.start();
		}
	}

	public abstract void doWork(String url);


	public boolean isRunThread() {
		return runThread;
	}
	public void close() {
		logInfo("close");
		this.runThread = false;
		try {
			Thread.sleep(100);
			workThread = null;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	

}
